# coding: utf-8
# @Author : lryself
# @Date : 2020/12/14 17:48
# @Software: PyCharm

from flask import current_app
from werkzeug.security import generate_password_hash

from ..models import db
from ..controller.userInfoController import UserInfoController
from ..utils import commons
from ..utils.response_code import RET


class UserInfoManager(UserInfoController):
    @classmethod
    def get_user(cls, user_id):
        '''
        给flask-login调用的方法
        :param user_id: 用户id
        :return:
        '''
        filter_list = []
        filter_list.append(cls.userID == user_id)

        try:
            student = db.session.query(cls).filter(*filter_list)
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，获取学生信息失败', 'error': str(e)}

        if not student.first():
            return {'code': RET.NODATA, 'msg': '无学生信息', 'error': '无学生信息'}

        # 处理返回的数据
        return {'code': RET.OK, 'msg': 'OK', 'data': student.first()}

    @classmethod
    def reset_password(cls, **kwargs):
        new_password = kwargs.get('password') if kwargs.get('password') else '123456'

        filter_list = []
        filter_list.append(cls.userID == kwargs.get('user_id'))

        try:

            user = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询用户信息失败', 'error': str(e)}

        if not user.first():
            return {'code': RET.NODATA, 'msg': '无用户信息', 'error': '无用户信息'}

        try:
            user.update({
                'password': generate_password_hash(new_password)
            })
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，重置用户密码失败', 'error': str(e)}

        data = commons.query_to_dict(user.first())

        back_data = {
            'user_id': data.get('user_id'),
            'new_password': data.get('password')
        }

        return {'code': RET.OK, 'msg': '重置密码成功', 'data': back_data}
